package idiolect.helpers;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.ArrayList;

public class HTMLDialog extends JDialog {
    public static final int ADD_TASK_ID = 16122009;
    public static final int REPLACE_TASK_ID = 17122009;

    public HTMLDialog(final Window owner, final String title, String html) throws IOException {
        super(owner, title);
        final JEditorPane pane = new JEditorPane();
        pane.setContentType("text/html");
        pane.setText(html);
        pane.setCaretPosition(0);
        pane.setEditable(false);
        getContentPane().setLayout(new GridLayout(1, 1));
        getContentPane().add(new JScrollPane(pane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
//        setSize(owner.getWidth()/2,owner.getHeight());
        setSize(400, 647);
        setLocationRelativeTo(owner);
        pane.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "doAdd");
        pane.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK), "doReplace");
        pane.getActionMap().put("doAdd", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                if (owner instanceof ResponseAcceptor) {
                    AbstractHelper.stub((ResponseAcceptor) owner, title, pane.getSelectedText(), ADD_TASK_ID).doRequest();
                }
            }
        });
        pane.getActionMap().put("doReplace", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                if (owner instanceof ResponseAcceptor) {
                    AbstractHelper.stub((ResponseAcceptor) owner, title,
                            pane.getSelectedText().replaceAll("\n", " ").trim(),
                            REPLACE_TASK_ID).doRequest();
                }
            }
        });

    }

    public void setVisible(boolean b) {
        Window[] windows = Window.getWindows();
        java.util.List<Window> toDispose = new ArrayList<Window>();
        for (Window window : windows) {
            if (window instanceof HTMLDialog && window != this) {
                if (!window.getBounds().isEmpty())
                    setBounds(window.getBounds());
                toDispose.add(window);
            }
        }
        super.setVisible(b);
        for (Window window : toDispose)
            window.dispose();
    }
}
